//
//  FunnyController.swift
//  FunnyReader
//
//  Created by yht on 2025/1/21.
//

import UIKit
import Photos
import AVFoundation

class FunPlayController: UIViewController, FunPlayViewDelegate, FuOcrLiteDelegate {
    
    
    lazy var funPlayView: FunPlayView = {
        let funPlayView = FunPlayView()
        funPlayView.delegate = self
        return funPlayView
    }()
    
    lazy var fuOcrLite: FuOcrLite = {
        let fuOcrLite = FuOcrLite()
        fuOcrLite.delegate = self
        return fuOcrLite
    }()
    
    func requestPhotoLibraryAuthorization() {
        PHPhotoLibrary.requestAuthorization { status in
            DispatchQueue.main.async {
                if status == .authorized {
                    // 授权成功
                } else {
                    // 授权被拒绝，显示提示信息
                }
            }
        }
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.blue
        view.addSubview(funPlayView)
        
        funPlayView.translatesAutoresizingMaskIntoConstraints = false
        
        // 设置 imageView 的约束
        NSLayoutConstraint.activate([
            funPlayView.topAnchor.constraint(equalTo: self.view.topAnchor),
            funPlayView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            funPlayView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            funPlayView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
        ])
        
        requestPhotoLibraryAuthorization()
    }
    
    

    func saveImageToAlbum(_ image: UIImage) {
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: image)
        }) { success, error in
            if success {
                print("Image saved to album successfully.")
            } else if let error = error {
                print("Error saving image to album: \(error)")
            }
        }
    }
    
    func didSelectedImage(image: UIImage) {
        synthesizer.stopSpeaking(at: AVSpeechBoundary.word)
        fuOcrLite.ocrDetection(image, padding: 50, maxSideLen: 0, boxScoreThresh: 0.6, boxThresh: 0.3, unClipRatio: 2.0, doAngle: true, mostAngle: true);
    }
    
    // 语音合成器实例
    let synthesizer = AVSpeechSynthesizer()
    func didRead() {
        guard ocrResult != nil else {
            return;
        }
        speak(text: ocrResult!.text)
    }
    
    func speak(text: String) {
        // 创建一个语音对象
        let utterance = AVSpeechUtterance(string: text)
        // 设置语音语言，这里以美式英语为例
        utterance.voice = AVSpeechSynthesisVoice(language: "zh-CN")  // 简体中文
        // 设置朗读速率，范围从0.0（非常慢）到1.0（非常快）
        utterance.rate = 0.5
        // 开始朗读
        synthesizer.speak(utterance)
    }
    
    var ocrResult : FunOcrResult?
    func doneDetection(_ result: FunOcrResult) {
        ocrResult = result
    }
}
